package com.b2c.repository.mall;

import com.b2c.entity.result.PagingResponse;
import com.b2c.common.third.sender.SMSHttpClient;
import com.b2c.common.third.templatemsg.WxSendTempletConstants;
import com.b2c.common.third.templatemsg.WxSendTempletMsg;
import com.b2c.common.third.templatemsg.WxSendTempletParms;
import com.b2c.entity.DataRow;
import com.b2c.entity.SysVariableEntity;
import com.b2c.entity.enums.VariableEnums;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description:系统通用功能 pbd add 2019/4/8 10:44
 */
@Repository
public class SystemRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 分页总页数
     *
     * @return
     */
    protected int getTotalSize() {
        return jdbcTemplate.queryForObject("SELECT FOUND_ROWS() as row_num;", int.class);
    }

    /**
     * 获取token
     *
     * @return
     */
    public String getToken() {
        return jdbcTemplate.queryForObject("select access_token from sys_token LIMIT 1", String.class);
    }

    /**
     * 添加更新系统参数
     *
     * @param key    key
     * @param remark 描述
     * @param value  值
     */
    public void updVariable(String key, String remark, String value) {
        String updVariable = "UPDATE sys_variable SET `value`=?,modify_on=unix_timestamp(now()),remark=? WHERE `key`=?";
        jdbcTemplate.update(updVariable, value, remark, key);
    }

    /**
     * 查询系统参数值
     *
     * @param key
     * @return
     */
    public SysVariableEntity getVariable(String key) {
        List<SysVariableEntity> list = jdbcTemplate.query("select * from sys_variable where `key`=?", new BeanPropertyRowMapper<>(SysVariableEntity.class), key);
        if (list == null || list.size() == 0) return null;
        return list.get(0);
    }

    /**
     * 获取站内信模板
     *
     * @param variable 消息类型
     * @param data     消息数据
     */
    public String getSendTemlete(VariableEnums variable, DataRow data) {
        SysVariableEntity var = getVariable(variable.name());
        DataRow temdata = new DataRow();
        switch (variable.name()) {
            case "MSG_ZFCG":
                temdata.set("PAY_MONEY", data.getBigDecimal("money"));
                temdata.set("GOODS_INFO", data.getString("info"));
                break;
            case "MSG_DDFH":
                temdata.set("NAME", data.getString("name"));
                temdata.set("CODE", data.getString("code"));
                break;
            case "MSG_TKCG":
                temdata.set("INFO", data.getString("info"));
                temdata.set("MONEY", data.getString("money"));
                break;
        }
        temdata.set("SYSTEM.SITE_NAME", "华衣云购");
        //temdata.set("datetime",new Timestamp(System.currentTimeMillis()));
        return processTemplate(var.getValue(), temdata);

    }

    public WxSendTempletParms getWxSendTemlete(VariableEnums variable, String wxOpenId, DataRow data) {
        WxSendTempletParms parms = new WxSendTempletParms();
        parms.url = getVariable(VariableEnums.URL_WAP_INDEX.name()).getValue();
        parms.openId = wxOpenId;
        switch (variable.name()) {
            case "MSG_ZFCG":
                parms.temletId = WxSendTempletConstants.ZFCG;
                parms.param_1 = data.getBigDecimal("money") + "";
                parms.param_2 = data.getString("info");
                break;
            case "MSG_DDFH":
                parms.temletId = WxSendTempletConstants.DDFH;
                parms.param_1 = data.getString("name");
                parms.param_2 = data.getString("code");
                break;
            case "MSG_TKCG":
                parms.temletId = WxSendTempletConstants.DDFH;
                parms.param_1 = data.getString("info");
                parms.param_2 = data.getString("money");
                break;
        }
        return parms;
    }

    /**
     * 发送站内信
     *
     * @param userId   用户id
     * @param variable 消息类型
     * @param sendType 0:全部发送，1:站内信+模板 2：短信+站内信
     */
    public void sendTemleteMsg(Integer userId, String mobile, VariableEnums variable, DataRow data, Integer sendType) throws Exception {
        String tempMsg = getSendTemlete(variable, data);
        String wxOpenId = jdbcTemplate.queryForObject("SELECT  IFNULL(wx_open_id,'') from user where id=?", String.class, userId);
        String addMsg = "INSERT INTO user_message set user_id=?,title=?,comment=?,create_on=unix_timestamp(now())";
        if (StringUtils.isEmpty(mobile))
            mobile = jdbcTemplate.queryForObject("SELECT  IFNULL(mobile,'') from user where id=?", String.class, userId);
        if (sendType == 0) {
            //发送站内信
            jdbcTemplate.update(addMsg, userId, variable.getDescription(), tempMsg);
            //发送模板消息
            String token = getVariable(VariableEnums.PARMS_TOKEN.name()).getValue();
            if (!StringUtils.isEmpty(wxOpenId))
                WxSendTempletMsg.sendTempletMsg(token, getWxSendTemlete(variable, wxOpenId, data));
            //发送短信
            if (!StringUtils.isEmpty(mobile)) SMSHttpClient.sendCodeSMS(mobile, tempMsg);
        }
        //发布站内信+模板
        if (sendType == 1) {
            jdbcTemplate.update(addMsg, userId, variable.getDescription(), tempMsg);
            //模板消息
            String token = getVariable(VariableEnums.PARMS_TOKEN.name()).getValue();
            System.out.println();
            if (!StringUtils.isEmpty(wxOpenId))
                WxSendTempletMsg.sendTempletMsg(token, getWxSendTemlete(variable, wxOpenId, data));
        }
        //发送短信+站内信
        if (sendType == 2) {
            jdbcTemplate.update(addMsg, userId, variable.getDescription(), tempMsg);
            if (!StringUtils.isEmpty(mobile)) SMSHttpClient.sendCodeSMS(mobile, tempMsg);
        }
    }

    /**
     * 信息模板参数格式化
     *
     * @param template 模版
     * @param params   参数
     * @return
     */
    private static String processTemplate(String template, Map<String, Object> params) {
        if (template == null || params == null)
            return null;
        StringBuffer sb = new StringBuffer();
        Matcher m = Pattern.compile("\\$\\{\\s*(\\w|\\.|-|_|\\$)+\\s*\\}").matcher(template);
        while (m.find()) {
            String param = m.group();
            Object value = params.get(param.substring(2, param.length() - 1));
            m.appendReplacement(sb, value == null ? "" : value.toString());
        }
        m.appendTail(sb);
        return sb.toString();
    }

    /**
     * 分页查询平台常量
     *
     * @param pageIndex
     * @param pageSize
     * @param name      常量名
     * @param key       常量key
     * @return
     */
    public PagingResponse<SysVariableEntity> getSysVariables(int pageIndex, int pageSize, String name, String key) {
        List<Object> params = new ArrayList<>();
        StringBuilder sb = new StringBuilder("select SQL_CALC_FOUND_ROWS * from sys_variable where 1=1 ");
        if (!StringUtils.isEmpty(key)) {
            sb.append(" AND remark like ? ");
            params.add("%" + name + "%");
        }
        if (!StringUtils.isEmpty(name)) {
            sb.append(" AND `key` =?");
            params.add(key);
        }
        sb.append(" ORDER BY modify_on DESC LIMIT ?,?");
        params.add((pageIndex - 1) * pageSize);
        params.add(pageSize);
        List<SysVariableEntity> sysRoleList = jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(SysVariableEntity.class), params.toArray(new Object[params.size()]));
        return new PagingResponse<>(pageIndex, pageSize, getTotalSize(), sysRoleList);
    }


}
